Golang : Output or print out JSON stream/encoded data
Problem :
You need to produce JSON stream or JSON encoded data to web browser or client. How to do that?
Solution :
Set the header Content-Type
to application/json
and write the http.ResponseWriter.
For example :
package main
import (
"net/http"
)
func Employees(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// NOTE : put jsonStr in a FOR loop to read forever from database and encode the data with
// json.Marshal() function to produce JSON stream
// see https://www.socketloop.com/tutorials/golang-convert-csv-data-to-json-format-and-save-to-file
// for this example, we will use static JSON string
jsonStr := `[{"Name":"Dennis","Age":16,"Job":"CEO"},
{"Name":"Eva","Age":34,"Job":"CFO"},
{"Name":"Paul","Age":28,"Job":"COO"}]`
// output to web or client
w.Write([]byte(jsonStr))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", Employees)
http.ListenAndServe(":8080", mux)
}
Reference :
https://www.socketloop.com/tutorials/golang-unmarshal-json-from-http-response
See also : Golang : Unmarshal JSON from http response
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+25.4k Golang : Convert long hexadecimal with strconv.ParseUint example
+16k Golang : Get sub string example
+7.1k Golang : Get Alexa ranking data example
+16k Golang : Read large file with bufio.Scanner cause token too long error
+30.1k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+35.1k Golang : Upload and download file to/from AWS S3
+22.2k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+11.5k Use systeminfo to find out installed Windows Hotfix(s) or updates
+5.2k Golang : Convert lines of string into list for delete and insert operation
+22.1k Golang : Repeat a character by multiple of x factor
+44.9k Golang : Use wildcard patterns with filepath.Glob() example
+15k Golang : package is not in GOROOT during compilation